const { task, parallel, series } = require("gulp")
const { execSync } = require("child_process")
const path = require("path")
const fs = require("fs")

const MODULES = [
    { name: "puremvc", dir: path.join("tools", "puremvc") },
]

function buildModule(module) {
    return function (cb) {
        try {
            const modulePath = path.join(__dirname, module.dir)
            const packageJsonPath = path.join(modulePath, "package.json")

            // 1. 检查 package.json 是否存在
            if (!fs.existsSync(packageJsonPath)) {
                throw new Error(`未找到 ${packageJsonPath}`)
            }

            // 2. 检查依赖是否安装
            if (!fs.existsSync(path.join(modulePath, "node_modules"))) {
                console.log(`安装 ${module.name} 依赖...`)
                execSync("yarn install", { cwd: modulePath, stdio: "inherit" })
            }

            // 3. 执行 gulp build
            const gulpPath = path.join(modulePath, "node_modules", ".bin", "gulp")
            execSync(`${gulpPath} build`, { cwd: modulePath, stdio: "inherit" })
            cb()
        } catch (e) {
            cb(new Error(`${module.name} 构建失败: ${e.message}`))
        }
    }
}

MODULES.forEach(module => {
    task(`build-${module.name}`, buildModule(module))
})

task("build-tools", parallel(...MODULES.map(m => `build-${m.name}`)))
task("default", series("build-tools"))
